import { Component,Fragment} from 'react';
// 引入编辑器组件
import BraftEditor from 'braft-editor'
// 引入编辑器样式
import 'braft-editor/dist/index.css'
import { ContentUtils } from 'braft-utils'//编辑器辅助类库
import {Card,Form,Spin,Switch,Select,Input,Button,Upload,Icon,message} from 'antd';
import moment from 'moment';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import styles from './Update.less';
import { connect } from 'dva';
import router from 'umi/router';
// import { setParam } from '@/utils/Base';
import FileManager from '@/components/FileManager';
//注入模型类 dispatch
const mapStateToProps = (state) => {
    const CategoryList = state['Category'].CategoryList;
    const ResourceData = state['Resource'].ResourceData;
    const FileList = state['AdminFile'].FileList;
    //console.log('aa',state);
    return {
      CategoryList,
      ResourceData,
      FileList
    };
};
@connect(mapStateToProps)
//把from对象加入到this.props里面
@Form.create()
export default class Update extends Component {
    state = {
        fromLoading:false,
        uploadFileCacheUrl:'',
        editorState: BraftEditor.createEditorState('<p></p>'),
        editorInfo:'<p></p>',
        uploadImages:[],//上传多图
        FileManager:{
            visible:false,
            onChange:[],//选择的图片
            modalLoading:false,
        },
    };
    /**
     * 前置函数 在页面加载时就执行的函数
     */
    componentDidMount = () => {
        this.getCategoryData();//获取文章分类数据
        if(this.props.location.query.id){//获取资源数据
            this.getResourceData(this.props.location.query.id)
        }else{
            this.getResourceData(0)
        }
    }
    /**
     * 从模型拉取文章分类数据
     */
    getCategoryData = ()=>{
        this.setState({
            fromLoading:true
        });
        this.props.dispatch({
            type: 'Category/select',
            callback:(e)=>{
                setTimeout(() => {
                    this.setState({ fromLoading: false });
                  },500);
            }
        });
    }
    getResourceData = (id=0)=>{
        this.setState({
            fromLoading:true
        });
        this.props.dispatch({
            type: 'Resource/find',
            payload:{id:id},
            callback:(e)=>{
                if(e.code !=1){
                    message.error(e.msg);
                }else{
                    this.setState({
                        editorState:BraftEditor.createEditorState(this.props.ResourceData.info),
                        uploadImages:this.props.ResourceData.images,
                    });
                    
                }
                setTimeout(() => {
                    this.setState({ fromLoading: false });
                  },500);
            }
        });
    }
    /**
     * 处理from表单提交
     */
    handleSubmit = (e) => {
        const { dispatch, form } = this.props;
        e.preventDefault();
        form.validateFieldsAndScroll((err, values) => {
            // const obj1 = {
            //     key1:'value1',
            //     key2:'value2'
            // }
            // const obj2 = {
            //     key3:'value3',
            //     key4:'value4'
            // }
            // const new_obj = Object.assign(obj1,obj2);

            // console.log('new_obj',new_obj);
            // //结果为：{key1: "value1", key2: "value2", key3: "value3", key4: "value4"}

            const param = Object.assign(values,{'info':this.state.editorInfo},{'images':this.state.uploadImages});//多个对象合并
            delete param.content;//删除对象指定属性
            console.log('values',param);
            if (!err) {
                if(this.props.ResourceData.id){
                    dispatch({
                        type: 'Resource/edit',
                        payload: {
                            id:this.props.ResourceData.id,
                            ...param
                        },
                        callback:(e)=>{
                            if(e.code){
                                if(e.code===1){
                                    router.push(`/content/active/index`);
                                    message.success(e.msg);
                                }else{
                                    message.error(e.msg);
                                }
                            }else{
                                message.error(`发生错误：${e}`);
                            }
                            
                        }
                    });
                }else{
                    dispatch({
                        type: 'Resource/insert',
                        payload: param,
                        callback:(e)=>{
                            if(e.code){
                                if(e.code===1){
                                    router.push(`/content/active/index`);
                                    message.success(e.msg);
                                }else{
                                    message.error(e.msg);
                                }
                            }else{
                                message.error(`发生错误：${e}`);
                            }
                        }
                    });
                }
            }
        });
    };
    /**
     * 文章分类生产option
     */
    getOption = list => {
        const { Option } = Select;
        if (!list || list.length < 1) {
        return (
            <Option key={0} value={0}>
            没有找到选项
            </Option>
        );
        }
        
        //console.log(typeof list);
        return list.map(item => (
        <Option key={item.category_id} value={item.category_id}>
            {item.showName}
            
        </Option>
        ));
    };
    /**
     * 文章分类生产option
     */
    getParentListOption = () => {
        const { list } = this.props.CategoryList;
        return this.getOption(Array.from(list));
    };
    handleEditorChange = (editorState)=>{
        // console.log('aaa',editorState.toHTML());
        this.setState({ editorInfo:editorState.toHTML() })
    };
    /**
     * 编辑器图片上传
     */
    uploadHandler = (param) => {
        // this.setState({
        //     editorState: ContentUtils.insertText(this.state.editorState, '你好啊！')
        //   })
        if (!param.file) {
        return false
        }
        console.log('param',param);
        //正确的代码
        this.props.form.setFieldsValue({
            content: ContentUtils.insertMedias(this.state.editorState, [{
                type: 'IMAGE',
                url: 'https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo_top_86d58ae1.png'
            }])
          })
        //错误的代码
        // this.setState({
        // editorState: ContentUtils.insertMedias(this.state.editorState, [{
        //     type: 'IMAGE',
        //     url: 'https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo_top_86d58ae1.png'
        // }])
        // })
        console.log(this.state.editorState.toHTML());
    };
    FileManagerHandleModalVisible = (flag=false) => {
        console.log(this.state.FileManager.onChange);
        if(flag === true){
            this.onPageChange();
            
        }
        const FileManager = this.state.FileManager;
        FileManager.visible = flag;
        this.setState({
            FileManager:FileManager
        });
    }
    onPageChange=(page=1,size=6)=>{
        const oldFileManager = this.state.FileManager;
        oldFileManager.modalLoading = true;
        this.setState({
            FileManager:oldFileManager
        });
        //去获取数据
        this.props.dispatch({
            type: 'AdminFile/uploadFileManagerListJson',
            payload:{
                page:page,
                size:size
            },
            callback:(e)=>{
                oldFileManager.modalLoading = false;
                this.setState({
                    FileManager:oldFileManager
                });
            }
        });
    }
    FileManagerOkHandle= ()=>{
        this.FileManagerHandleModalVisible();
        const newChangeList = [];
        this.state.FileManager.onChange.map(function(value,key){
            newChangeList.push({
                type: 'IMAGE',
                url: value
            });
        });
        console.log('newChangeList',newChangeList);
        this.props.form.setFieldsValue({
            content: ContentUtils.insertMedias(this.state.editorState, newChangeList)
        })
        
        const oldFileManager = this.state.FileManager;
        oldFileManager.onChange = [];
        this.setState({
            FileManager:oldFileManager
        });
        
    }
    FileManagerhandleModalVisible = ()=>{
        this.FileManagerHandleModalVisible();
    }
    onFileUpload=(info)=>{
        console.log(info.file);
        if (info.file.status !== 'uploading') {
            
        }
        // console.log(info.file);

        if (info.file.status === 'done' && info.file.response.code === 1) {
            
            message.success(`上传成功`);
            this.onPageChange();
        } else if (info.file.status === 'error') {
            message.error(`上传失败${info.file.response.msg}`);
        }
    }
    /**
     * 修改名称
     */
    editFileName=(e)=>{
        console.log('修改名称',e);
    }
    /**
     * 修改分组
     */
    editFileGroup = (e)=>{
        console.log('修改分组',e);
    }
    /**
     * 复制链接
     */
    copyFileLink = (e) =>{
        console.log('复制链接',e);
    }
    /**
     * 删除附件
     */
    deleteFile = (id)=>{
        const oldFileManager = this.state.FileManager;
        oldFileManager.removeButtonLoading = true;
        this.setState({
            FileManager:oldFileManager
        });
        this.props.dispatch({
            type: 'AdminFile/removeFile',
            payload:{
                id:id,
            },
            callback:(e)=>{
                if(e.code===1){
                    this.onPageChange();
                }
                oldFileManager.removeButtonLoading = false;
                this.setState({
                    FileManager:oldFileManager
                });
            }
        });
        console.log('删除附件',id);
    }
    /**
     * 模态框点击确定触发
     */
    cardOnClick = (status,e)=>{
        // console.log('模态框点击确定触发',e);
        const FileManager = this.state.FileManager;
        //数组去重
        console.log(FileManager.onChange.includes(e));
        if(status == true){
            FileManager.onChange.includes(e)===false ? FileManager.onChange.push(e):'';
        }else{
            delete FileManager.onChange[FileManager.onChange.splice(e,1)];
        }
        
        
        console.log(FileManager.onChange);
        console.log('this.state.editorInfo',this.state.editorInfo);
        this.setState({
            FileManager:FileManager
        });
    }
    render(){
        const that = this;
        //console.log('this.props.ResourceData.images',this.props.ResourceData.images);
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 4 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 20 },
                md: { span: 20 },
            },
        };
    
        const submitFormLayout = {
            wrapperCol: {
                xs: { span: 24, offset: 0 },
                sm: { span: 10, offset: 7 },
            },
        };
        /**
         * 上传需要配置的参数
         */
        const uploadProps = {
            accept: 'image/*',
            name: 'upfile',
            action: '/server/api/admin/v1/upload/FileJson',
            //action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
            listType: 'picture-card',
            defaultFileList:that.props.ResourceData.images,
            supportServerRender:true,
            onChange(info) {
                if (info.file.status !== 'uploading') {
                //console.log(info.file, info.fileList);
                }
                console.log(info.file);
                if (info.file.status === 'done' && info.file.response.code === 1) {
                    const {uploadImages} = that.state;
                    uploadImages.push({image_cover:info.file.response.data.url});
                    that.setState({
                        uploadImages:uploadImages,
                        uploadFileCacheUrl:info.file.response.data.url
                    });
                    console.log('info.file.response',info.file.response);
                    message.success(`上传成功`);
                } else if (info.file.status === 'error') {
                    message.error(`上传失败${info.file.response.msg}`);
                }
            },
            previewFile(file) {
              
              console.log('Your upload file:', file);
              
              // Your process logic. Here we just mock to the same file
              return fetch('https://next.json-generator.com/api/json/get/4ytyBoLK8', {
                method: 'POST',
                body: file,
              }).then(res => res.json()).then(() => {
                  console.log('that.state.uploadFileCacheUrl',that.state.uploadFileCacheUrl);
                  return that.state.uploadFileCacheUrl;
              });
            },
          };
         /**
          * 编辑器需要的功能配置参数
          */
        const controls = [
            'undo', 'redo', 'separator',
            'font-size', 'line-height', 'letter-spacing', 'separator',
            'text-color', 'bold', 'italic', 'underline', 'strike-through', 'separator',
            'superscript', 'subscript', 'remove-styles', 'emoji',  'separator', 'text-indent', 'text-align', 'separator',
            'headings', 'list-ul', 'list-ol', 'blockquote', 'code', 'separator',
            'link', 'separator', 'hr', 'separator',
            // 'media', //删除编辑器自带的媒体库
            'antd-uploader',//自定义上传按钮
            'separator',
            'clear'
        ];
        /**
         * 编辑器用图片上传不用base64
         */
        const extendControls = [
            {
              key: 'antd-uploader',
              type: 'component',
              component: (
                // <Upload
                //   accept="image/*"
                //   action="/server/api/admin/v1/upload/FileJson"
                //   name="upfile"
                //   showUploadList={false}
                //   data={setParam()}
                //   customRequest={this.uploadHandler}
                // // onChange={(info)=>{
                // //     if (info.file.status !== 'uploading') {
                // //     //console.log(info.file, info.fileList);
                // //     }
                // //     console.log(info.file);
                // //     if (info.file.status === 'done' && info.file.response.code === 1) {
                        
                // //         that.setState({
                // //             editorState: ContentUtils.insertMedias(that.state.editorState, [{
                // //                 type: 'IMAGE',
                // //                 url: info.file.response.data.url
                // //             }])
                // //         })
                // //         console.log('editorState',that.state.editorState.toHTML());
                // //         message.success(`上传成功`);
                // //     } else if (info.file.status === 'error') {
                // //         message.error(`上传失败${info.file.response.msg}`);
                // //     }
                // // }}
                // >
                //   {/* 这里的按钮最好加上type="button"，以避免在表单容器中触发表单提交，用Antd的Button组件则无需如此 */}
                  
                // </Upload>
                <button type="button" className="control-item button upload-button" onClick={()=>{
                    this.FileManagerHandleModalVisible(true);
                    // console.log(this.state.FileManager.visible);
                }} data-title="插入图片">
                    <Icon type="picture" theme="filled" />
                  </button>
              )
            }
          ]
        return (
            <>
            <PageHeaderWrapper>
                <div className={styles.updateCard}>
                    <Card>
                        <Spin spinning={this.state.fromLoading}>
                            <Form onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 8 }}>
                                <Form.Item {...formItemLayout} label="文章标题">
                                    {this.props.form.getFieldDecorator('name', {
                                        initialValue:this.props.ResourceData.name,
                                        rules: [{ required: true, message: '请输入最少3个最多200个字符的值', min: 3 ,max:200}],
                                    })(<Input placeholder="请输入文章标题" />)}
                                </Form.Item>
                                {/* <Form.Item {...formItemLayout} label="文章简介">
                                    {this.props.form.getFieldDecorator('description', {
                                        initialValue:this.props.ResourceData.description,
                                        rules: [{ required: false, message: '最多200个字符的值', min: 3 ,max:200}],
                                    })(<Input.TextArea
                                        style={{ minHeight: 32 }}
                                        placeholder="请输入文章简介"
                                        rows={4}
                                      />)}
                                </Form.Item> */}
                                <Form.Item {...formItemLayout} label="文章分类">
                                    <div>
                                        {this.props.form.getFieldDecorator('category_id', {
                                            initialValue: this.props.ResourceData.category_id,
                                            rules: [{ required: true, message: '请选择父菜单' }],
                                        })(
                                            <Select showSearch placeholder="请选择" disabled={false} style={{ width: '100%' }}>
                                            {
                                                this.getParentListOption()
                                            }
                                            
                                            </Select>
                                        )}
                                    </div>
                                </Form.Item>   
                                {/* <Form.Item {...formItemLayout} label="文章封面&可上传多图">
                                    <div>
                                        <Upload {...uploadProps}>
                                        <Button>
                                            <Icon type="upload" /> Upload
                                        </Button>
                                        </Upload>
                                    </div>
                                </Form.Item> */}
                                <Form.Item {...formItemLayout} label="文章内容">
                                    {this.props.form.getFieldDecorator('content', {
                                        validateTrigger: 'onBlur',
                                        initialValue:this.state.editorState,
                                        rules: [{
                                            required: true,
                                            validator: (_, value, callback) => {
                                            if (value.isEmpty() === true) {
                                                callback('请输入正文内容')
                                            } else {
                                                callback()
                                            }
                                            }
                                        }],
                                        })(
                                            <BraftEditor
                                            // value={this.state.editorState}
                                            controls={controls}
                                            className={styles.my_editor}
                                            // excludeControls={'media'}
                                            onChange={this.handleEditorChange}
                                            onBlur={(e)=>{
                                                //console.log(e.toHTML());
                                            }}
                                            onSave={this.submitContent}
                                            extendControls={extendControls}
                                        />
                                        )}
                                </Form.Item>
                                <Form.Item {...formItemLayout} label="文章排序">
                                    {this.props.form.getFieldDecorator('sort', {
                                        initialValue:this.props.ResourceData.sort,
                                        rules: [{ required: false, message: '请输入最多2个字符的值' }],
                                    })(<Input placeholder="请输入文章排序" />)}
                                </Form.Item>
                                <Form.Item {...formItemLayout} label="是否启用">
                                    {this.props.form.getFieldDecorator('status', {
                                        valuePropName:'checked',
                                        initialValue:this.props.ResourceData.status
                                    })(<Switch checkedChildren="显示" unCheckedChildren="隐藏" />)}
                                </Form.Item>
                                <Form.Item {...formItemLayout} label="文章排序">
                                    {this.props.form.getFieldDecorator('sort', {
                                        initialValue:this.props.ResourceData.sort,
                                        rules: [{ required: false, message: '请输入最多2个字符的值' }],
                                    })(<Input placeholder="请输入文章排序" />)}
                                </Form.Item>
                                <Form.Item {...submitFormLayout} style={{ marginTop: 32 }}>
                                    <Button type="primary" htmlType="submit">
                                        保存
                                    </Button>
                                </Form.Item>
                            </Form>
                        </Spin>
                    </Card>
                </div>
            </PageHeaderWrapper>
            <FileManager
                FileManagerVisible={this.state.FileManager.visible}
                modalLoading={this.state.FileManager.modalLoading}
                FileManagerOkHandle = {this.FileManagerOkHandle}
                FileManagerhandleModalVisible = {this.FileManagerhandleModalVisible}
                FileList={this.props.FileList}
                editFileName={this.editFileName}
                copyFileLink={this.copyFileLink}
                editFileGroup={this.editFileGroup}
                deleteFile={this.deleteFile}
                cardOnClick={this.cardOnClick}
                onFileUpload={this.onFileUpload}
                onPageChange={this.onPageChange}
                FileManager={this.state.FileManager}     
            ></FileManager>
            </>
        )
    }
}